/**
 * @date 2016/01/31
 * @author ciwyaitd
 * @desc [funApp]
 */

var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    runSequence = require('run-sequence'),
    reload = browserSync.reload,
    plugins = require('gulp-load-plugins')();

var filePath = {
        swig: './resource/html/*.html',
        swigTpm: './resource/html/commonTpl/*.html',
        sass: ['./resource/src/sass/*.scss', './resource/src/sass/*/*.scss'],
        views_js: ['./resource/js/views/*.js','./resource/js/common/*.js'],
        lib_js: ['./resource/static/lib/*.js'],
        img: ['./resource/static/images/**.*'],
        fonts: ['./resource/static/fonts/**.*'],

        dist_lib_js: './build/static/js',
        dist_swig: './build/html',
        dist_img: './build/static/images',
        dist_font: './build/static/fonts',
        dist_js: './build/src/js',
        dist_css: './build/src/css',

        tmp: './.tmp/',
        build: './build/'
    },
    watchPath = {
        swig: 'resource/html/*.html',
        swigTpm: 'resource/html/commonTpl/*.html',
        sass: ['resource/src/sass/*.scss', 'resource/src/sass/*/*.scss'],
        views_js: ['resource/js/views/*.js','resource/js/common/*.js'],
        lib_js: ['resource/static/lib/*.js']
    },
    DEV = process.env.DEV || '';

/*---------- clean ----------*/
gulp.task('clean', function ( ) {
    return gulp.src([filePath.build,filePath.tmp], {read: false}).pipe(plugins.clean());
});

/* ------------- build ------------- */
// 编译scss文件
gulp.task('sass', function ()  {
    var gulpTask = gulp.src(filePath.sass)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the errored task
                this.emit('end') }
        }))
        .pipe(plugins.sass({
            outputStyle: 'compressed'
        }))
        .pipe(plugins.autoprefixer())
        .pipe(plugins.plumber.stop());

    gulpTask = DEV ? gulpTask : gulpTask.pipe(plugins.cached('sass_compile'));
    gulpTask = gulpTask.pipe(gulp.dest(filePath.dist_css));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'sass completed!'})) : gulpTask;
    return gulpTask;
});

// viewjs 压缩
gulp.task('jsViewUglify', function () {
    var gulpTask = gulp.src(filePath.views_js)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the errored task
                this.emit('end') }
        }))
        .pipe(plugins.sourcemaps.init());

    gulpTask = DEV ? gulpTask :
        gulpTask.pipe(plugins.changed(filePath.tmp))
            .pipe(gulp.dest(filePath.tmp));

    gulpTask = gulpTask.pipe(plugins.babel({
            presets: ['es2015', 'react']
        }))
        .pipe(plugins.uglify())
        .pipe(plugins.sourcemaps.write('./maps'))
        .pipe(gulp.dest(filePath.dist_js));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'jsViewUglify completed!'})) : gulpTask;
    return gulpTask;
});

// libjs 压缩
gulp.task('jsLibUglify', function () {
        var gulpTask = gulp.src(filePath.lib_js)
            .pipe(plugins.concat('static.min.js'))
            .pipe(plugins.plumber({
                errorHandler: function(err) {
                    // display the error message
                    console.log(err);
                    // end the error task
                    this.emit('end') }
            }))
            .pipe(plugins.sourcemaps.init());
        gulpTask = DEV ? gulpTask :
            gulpTask.pipe(plugins.changed(filePath.tmp))
                .pipe(gulp.dest(filePath.tmp));

        gulpTask = gulpTask.pipe(plugins.babel({
                presets: ['es2015', 'react']
            }))
            .pipe(plugins.uglify())
            .pipe(plugins.sourcemaps.write('./maps'))
            .pipe(gulp.dest(filePath.dist_lib_js));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'jsLibUglify completed!'})) : gulpTask;
    return gulpTask;
});

// 编译swig模板
gulp.task('distSwig', function () {
    var gulpTask = gulp.src(filePath.swig)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the error task
                this.emit('end') }
        }));
    gulpTask = !DEV ? gulpTask.pipe(plugins.changed( filePath.dist_swig, {extension: '.html'}))// 检测模板文件是否发生更改
        : gulpTask.pipe(plugins.replace(/src=\"..\/public\/js\/views\//, 'inline src="../../rootJs/'));// 生产环境替换js src

    gulpTask = gulpTask.pipe(plugins.swig({defaults: { cache: false }}));
    gulpTask = DEV ? gulpTask.pipe(plugins.inlineSource()) : gulpTask;// 生产环境将js内联化
    gulpTask = gulpTask.pipe(gulp.dest(filePath.dist_swig));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'distSwig completed!'})) : gulpTask;
    return gulpTask;
});

// imagemin 压缩图片
gulp.task('distImg', function () {
    return gulp.src(filePath.img)
        .pipe(plugins.changed(filePath.dist_img))
        .pipe(plugins.imagemin())
        .pipe(gulp.dest(filePath.dist_img));
});

// fonts move to build
gulp.task('distFont', function () {
    return gulp.src(filePath.fonts)
        .pipe(plugins.changed(filePath.dist_font))
        .pipe(gulp.dest(filePath.dist_font));
});

// 平移不公共js
gulp.task('distLib', function () {
    return gulp.src(filePath.lib_js)
        .pipe(gulp.dest(filePath.dist_lib_js))
        .pipe(plugins.changed(filePath.dist_lib_js))
        .pipe(plugins.notify({message: 'distLib completed!'}));
});

// pro: run on server 服务器运行
gulp.task('proRun', ['clean'], function () {
    runSequence('jsViewUglify',
        ['distImg', 'distFont', 'distLib'],
        ['distSwig', 'sass']);
});

// 监控修改reload浏览器
gulp.task('allReload', ['sass', 'jsViewUglify', 'distSwig'], function () {
    reload();
});

// 运行相关任务和启动服务器
gulp.task('server', ['distImg', 'distFont', 'distLib', 'distSwig', 'sass', 'jsLibUglify', 'jsViewUglify'], function () {
    browserSync({
        port: 9000,
        server: {
            baseDir: './build/',
            directory: true
        }
    });
    gulp.watch(
        [watchPath.swig].concat(watchPath.swigTpm, watchPath.sass, watchPath.views_js, watchPath.lib_common_js)
        , ['allReload']);//.on('change', reload);
});